// 1. 数字操作
// 1.1 生成指定范围随机数
export function getRandomNumber(min: number, max: number): number {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

// 2. 数组操作
// 2.1 数组乱序
export function shuffleArray<T>(arr: T[]): T[] {
    return [...arr].sort(() => Math.random() - 0.5);
}

// 2.2 数组扁平化
export function flattenArray<T>(arr: T[]): T[] {
    return arr.flat(Infinity) as T[];
}

// 2.3 从数组中获取随机元素
export function getRandomElement<T>(arr: T[]): T {
    return arr[Math.floor(Math.random() * arr.length)];
}

// 3. 字符串操作
// 3.1 生成随机字符串
export function generateRandomString(length: number = 16): string {
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
}

// 3.2 字符串首字母大写
export function capitalizeFirstLetter(str: string): string {
    if (!str) return str;
    return str.charAt(0).toUpperCase() + str.slice(1);
}

// 3.3 手机号中间四位变成*
export function formatPhoneNumber(phone: string): string {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}

// 3.4 驼峰命名转换成短横线命名
export function camelToKebab(str: string): string {
    return str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
}

// 3.5 短横线命名转换成驼峰命名
export function kebabToCamel(str: string): string {
    return str.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
}

// 4. 金额转换
// 4.1 数字转化为大写金额
export function numberToChineseCurrency(num: number | string): string {
    if (isNaN(Number(num)) || Number(num) === 0) return '零元整';
    const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    const units = [
        ['', '拾', '佰', '仟'],
        ['万', '拾万', '佰万', '仟万'],
        ['亿', '拾亿', '佰亿', '仟亿'],
        ['兆', '拾兆', '佰兆', '仟兆']
    ];
    const decimalUnits = ['角', '分'];

    let result = '';
    let numStr = Number(num).toString();

    // 处理整数部分
    if (numStr.includes('.')) {
        const parts = numStr.split('.');
        numStr = parts[0];
        const decimalPart = parts[1].padEnd(2, '0').substring(0, 2);

        // 处理小数部分（角分）
        for (let i = 0; i < decimalPart.length; i++) {
            const digit = parseInt(decimalPart[i]);
            if (digit !== 0) {
                result += digits[digit] + decimalUnits[i];
            }
        }

        if (result === '') {
            result = '整';
        }
    } else {
        result = '整';
    }

    // 处理整数部分
    let integerPart = numStr;
    let unitIndex = 0;

    while (integerPart.length > 0) {
        const part = integerPart.slice(-4);
        integerPart = integerPart.slice(0, -4);

        let partResult = '';
        for (let i = 0; i < part.length; i++) {
            const digit = parseInt(part[i]);
            if (digit !== 0) {
                partResult += digits[digit] + units[0][part.length - 1 - i];
            } else {
                // 处理零的情况
                if (i < part.length - 1 && parseInt(part[i + 1]) !== 0 && !partResult.endsWith('零')) {
                    partResult += '零';
                }
            }
        }

        if (partResult !== '') {
            result = partResult + units[Math.floor(unitIndex / 4)][unitIndex % 4] + result;
        }

        unitIndex++;
    }

    // 处理特殊情况
    result = result.replace(/零+/g, '零');
    result = result.replace(/零([万亿兆])/g, '$1');
    result = result.replace(/^零+/, '');
    result = result.replace(/亿万/, '亿');

    return result + '元';
}

// 5. localStorage 操作
// 5.1 存储 localStorage
export function setLocalStorage<T>(key: string, value: T): void {
    try {
        localStorage.setItem(key, JSON.stringify(value));
    } catch (e) {
        console.error('Failed to set localStorage:', e);
    }
}

// 5.2 获取 localStorage
// export function getLocalStorage<T>(key: string, defaultValue: T = null): T {
//     try {
//         const value = localStorage.getItem(key);
//         return value ? JSON.parse(value) : defaultValue;
//     } catch (e) {
//         console.error('Failed to get localStorage:', e);
//         return defaultValue;
//     }
// }

// 5.3 删除 localStorage
export function removeLocalStorage(key: string): void {
    localStorage.removeItem(key);
}

// 6. Cookie 操作
// 6.1 设置 cookie
export function setCookie(name: string, value: string, days: number = 7): void {
    let expires = '';
    if (days) {
        const date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = '; expires=' + date.toUTCString();
    }
    document.cookie = name + '=' + (value || '') + expires + '; path=/';
}

// 6.2 读取 cookie
export function getCookie(name: string): string | null {
    const nameEQ = name + '=';
    const ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

// 7. 正则校验
// 7.1 校验身份证号码
export function validateIDCard(idCard: string): boolean {
    const regex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    return regex.test(idCard);
}

// 7.2 校验是否包含中文
export function containsChinese(str: string): boolean {
    const regex = /[\u4e00-\u9fa5]/;
    return regex.test(str);
}

// 8. URL 参数操作
// 8.1 获取 URL 参数列表
export function getURLParams(url: string = window.location.href): Record<string, string> {
    const params = {};
    const queryString = url.split('?')[1];
    if (!queryString) return params;

    const keyValuePairs = queryString.split('&');
    for (const pair of keyValuePairs) {
        const [key, value] = pair.split('=');
        params[decodeURIComponent(key)] = decodeURIComponent(value || '');
    }
    return params;
}

// 8.3 键值对拼接成 URL 参数
export function buildURLParams(params: Record<string, string | number | boolean>): string {
    return Object.entries(params)
        .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
        .join('&');
}

// 9. 设备和系统检测
// 9.1 判断是移动还是 PC 设备
export function isMobileDevice(): boolean {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

// 9.4 判断是 Windows 还是 Mac 系统
export function getOperatingSystem(): 'Windows' | 'MacOS' | 'Other' {
    const userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.indexOf('win') !== -1) return 'Windows';
    if (userAgent.indexOf('mac') !== -1) return 'MacOS';
    return 'Other';
}

// 10. DOM 操作
// 10.1 滚动到页面顶部
export function scrollToTop(): void {
    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
}

// 10.4 获取可视窗口高度
export function getViewportHeight(): number {
    return window.innerHeight || document.documentElement.clientHeight;
}

// 11. 时间操作
// 11.2 格式化时间
export function formatDate(date: Date | string | number, format: string = 'YYYY-MM-DD HH:mm:ss'): string {
    if (!(date instanceof Date)) {
        date = new Date(date);
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    const second = String(date.getSeconds()).padStart(2, '0');

    return format
        .replace('YYYY', String(year))
        .replace('MM', month)
        .replace('DD', day)
        .replace('HH', hour)
        .replace('mm', minute)
        .replace('ss', second);
}

// 12. 函数优化
// 12.2 防抖函数
export function debounce<T extends (...args: any[]) => any>(func: T, wait: number, immediate: boolean = false): T {
    let timeout: ReturnType<typeof setTimeout> | null;
    return function(this: any, ...args: Parameters<T>): ReturnType<T> {
        const context = this;
        const later = () => {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        const callNow = immediate && !timeout;
        if (timeout) clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) return func.apply(context, args) as ReturnType<T>;
        return undefined as ReturnType<T>;
    } as T;
}

// 12.3 节流函数
export function throttle<T extends (...args: any[]) => any>(func: T, limit: number): T {
    let inThrottle: boolean;
    return function(this: any, ...args: Parameters<T>): ReturnType<T> {
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
        return undefined as ReturnType<T>;
    } as T;
}

// 12.5 对象深拷贝
export function deepClone<T>(obj: T): T {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }

    if (obj instanceof Date) {
        return new Date(obj.getTime()) as any;
    }

    if (obj instanceof Array) {
        return obj.map(item => deepClone(item)) as any;
    }

    const clone = {} as T;
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            clone[key] = deepClone(obj[key]);
        }
    }
    return clone;
}    